package de.mpii.struct.tree;

import java.util.ArrayList;
import java.util.List;

import de.mpii.util.Uformat;

public class Tree<T> {

	private final TreeNode<T> root = new TreeNode<T>();

	public Tree() {

	}

	public List<TreeNode<T>> getLeaves() {
		List<TreeNode<T>> list = new ArrayList<TreeNode<T>>();

		getLeaves(root, list);

		return list;
	}

	private void getLeaves(TreeNode<T> node, List<TreeNode<T>> list) {
		if (node.isLeaf()) {
			list.add(node);
			return;
		}

		for (TreeNode<T> child : node.getChildren())
			getLeaves(child, list);
	}

	public TreeNode<T> getRoot() {
		return root;
	}

	@Override
	public String toString() {
		StringBuilder sbuilder = new StringBuilder();

		toString(root, sbuilder, 0);

		return sbuilder.toString();
	}

	private void toString(TreeNode<T> node, StringBuilder sbuilder, int level) {
		sbuilder.append(Uformat.repeat(" ", 4 * level));
		sbuilder.append(node.getObject());
		sbuilder.append("\n");

		for (TreeNode<T> child : node.getChildren())
			toString(child, sbuilder, level + 1);
	}
}
